import { getPageList, addOrUpdate } from '@/api/trademark';
import type { TrademarkListInfoData, TrademarkData } from '@/api/trademark'
import React, { useEffect, useState } from 'react';
import { Button, Space, Table, Card, message, Modal, Form, Input, Upload } from 'antd';
import { EditOutlined, DeleteOutlined, PlusOutlined, LoadingOutlined } from "@ant-design/icons";
import { RcFile, UploadChangeParam, UploadFile, UploadProps } from 'antd/lib/upload';

function Index() {
    const [form] = Form.useForm()
    // 定义保存品牌管理列表的数据状态
    const [trademarkList, setTrademarkList] = useState([])
    // 定义弹出层的标题
    const [modalTitle, setModalTitle] = useState("添加品牌")
    // 定义保存页码信息的数据状态
    const [pageInfo, setPageInfo] = useState({
        current: 1,
        pageSize: 4,
        total: 4
    })
    // 定义新增的品牌：是一个对象
    const [tmForm, setTmForm] = useState({
        id: '',
        tmName: '',
        logoUrl: ''
    })
    // 【表单验证】
    // 自定义验证规则的验证器函数
    // rule代表规则本身 用来占位 value代表用户输入的数据 callback代表验证通过(不传递参数)或不通过(传递参数：错误对象)
    const checkTmName = (rule: any, value: any, callback: any) => {
        if (value.length < 2 || value.length > 20) {
            callback(new Error('品牌名称长度必须在2-20之间'))
        } else {
            callback()
        }
    }

    // 定义加载中状态
    const [loading, setLoading] = useState(false)
    // 定义对话框弹出状态
    const [isModalOpen, setIsModalOpen] = useState(false);
    // 定义图片地址
    const [imageUrl, setImageUrl] = useState('')

    // 【弹出对话框】
    const showModal = (data: any) => {
        setIsModalOpen(true);
        form.resetFields()
        setImageUrl(data.logoUrl)
    }
    // 确认
    const handleOk = () => {
        // 清空表单
        form.resetFields()
        // 关闭对话框
        setIsModalOpen(false)
    };
    // 【关闭弹框】
    const handleCancel = () => {
        // 清空表单
        form.resetFields()
        // 关闭对话框
        setIsModalOpen(false)
    };

    // 限制用户上传的图片格式和大小
    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };


    // 处理上传
    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            // setLoading(true);
            return;
        }
        if (info.file.status === 'done') {

            setImageUrl(info.file.response.data);

        }
    };
    // 上传按钮
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    )

    // 封装：【发送请求获取分页列表、页码改变】
    const getTrademarkList = async function (current: number = 1, pageSize: number = 4) {
        // 发送请求之前开始loading
        setLoading(true)
        try {
            const res: any = await getPageList(current, pageSize)
            setTrademarkList(res.data.records)
            setPageInfo({
                current: res.data.current,
                pageSize: res.data.size,
                total: res.data.total
            })
        } catch (error) {
            message.open({
                type: 'error',
                content: '获取品牌列表数据失败',
            })
        }
        // 发送请求结束结束loading
        setLoading(false)
    }

    useEffect(() => {
        // 发请求
        getTrademarkList()
    }, [])

    useEffect(() => {
        if (tmForm) form.setFieldsValue(tmForm)
    }, [tmForm])

    return (
        <div id={"content"}>
            <Card>
                <div style={{ marginBottom: 20 }}>
                    <Button onClick={showModal} type="primary" icon={<PlusOutlined />}>添加</Button>
                    <Modal forceRender title={modalTitle} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}>
                        <Form
                            form={form}
                            name="basic"
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 16 }}
                            // initialValues={tmForm}
                            // onFinish 点击按钮符合规则的回调
                            onFinish={async (values) => {
                                // values可以拿到输入表单的数据
                                console.log(values);

                                if (values.id) {
                                    values.logoUrl = imageUrl
                                    console.log(values);

                                    await addOrUpdate({ ...values })
                                } else {
                                    let obj = {
                                        tmName: values.tmName,
                                        logoUrl: values.logoUrl.file.response.data
                                    }
                                    await addOrUpdate(obj)
                                }
                                console.log(values)
                                // 关闭表单
                                setIsModalOpen(false)
                                // 清空表单
                                form.resetFields()
                            }}
                            // onFinishFailed={onFinishFailed}
                            autoComplete="off"
                        >
                            <Form.Item
                                label="id"
                                name="id"
                                hidden
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                label="品牌名称"
                                name="tmName"
                                rules={[{
                                    required: true,
                                    message: '品牌名称不能为空！',
                                    validator: checkTmName
                                }]}
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                label="品牌LOGO"
                                name="logoUrl"
                                rules={[{ required: true, message: '请上传品牌LOGO！' }]}
                            >
                                <Upload
                                    listType="picture-card"
                                    className="avatar-uploader"
                                    showUploadList={false}
                                    action="http://gmall-h5-api.atguigu.cn/admin/product/fileUpload"
                                    beforeUpload={beforeUpload}
                                    onChange={handleChange}
                                >
                                    {imageUrl ? <img src={imageUrl} style={{ width: '100%' }} /> : uploadButton}
                                </Upload>
                            </Form.Item>

                            <Form.Item wrapperCol={{ offset: 16, span: 8 }}>
                                <Space>
                                    <Button type="primary" htmlType="submit">
                                        确定
                                    </Button>
                                    <Button onClick={() => {
                                        form.resetFields()
                                        setIsModalOpen(false)
                                    }} htmlType="button">
                                        取消
                                    </Button>
                                </Space>
                            </Form.Item>
                        </Form>
                    </Modal>
                </div>
                <Table
                    loading={loading}
                    pagination={{
                        ...pageInfo,
                        onChange(current, pageSize) {
                            getTrademarkList(current, pageSize)
                        }
                    }}
                    bordered={true}
                    rowKey={"id"}
                    columns={[
                        {
                            title: "序号",
                            align: "center",
                            render(value, rows, index) {
                                return (pageInfo.current - 1) * pageInfo.pageSize + index + 1
                            }
                        }, {
                            title: "品牌名称",
                            align: "center",
                            dataIndex: "tmName"
                        }, {
                            title: "品牌LOGO",
                            align: "center",
                            dataIndex: "logoUrl",
                            render(logoUrl) {
                                return (
                                    <img height={50} src={logoUrl} />
                                )
                            }
                        }, {
                            title: "操作",
                            align: "center",
                            render(rows) {
                                return (
                                    <Space>
                                        <Button
                                            onClick={() => {
                                                console.log(rows)
                                                setTmForm({ ...rows })
                                                // 弹出模态框
                                                showModal({ ...rows })
                                                // 标题
                                                setModalTitle('修改品牌')
                                            }} size='small' type="primary" icon={<EditOutlined />}>
                                            修改
                                        </Button>
                                        <Button size='small' danger type="primary" icon={<DeleteOutlined />}>删除</Button>
                                    </Space>
                                )
                            }
                        }
                    ]}
                    dataSource={trademarkList}
                />
            </Card >
        </div >
    );
}

export default Index;